module Admins
  class ChargesController < ControllerBase
    before_action :set_plan, only: [:index, :create]
    before_action :set_charge, only: [:show, :update, :destroy]
    before_action :validate_plan_inactiveness, only: [:create, :update, :destroy]

    def index
      @charges = @plan.charges.page(params[:page]).per(params[:per])
      render json: @charges
    end

    def show
      render json: @charge
    end

    def create
      @charge = @plan.charges.build(charge_params)
      if @charge.save
        # expire_cache "plans:index" do
          render json: @charge, status: :created, location: [:admins, @charge]
        # end
      else
        render json: @charge.errors, status: :unprocessable_entity
      end
    end

    def update
      if @charge.update(charge_params)
        # expire_cache "plans:index" do
          head :no_content
        # end
      else
        render json: @charge.errors, status: :unprocessable_entity
      end
    end

    def destroy
      if @charge.destroy
        # expire_cache "plans:index" do
          head :no_content
        # end
      else
        render json: @charge.errors, status: :unprocessable_entity
      end
    end

    private

    def set_charge
      @charge = Charge.find(params[:id])
    end

    def set_plan
      @plan = Plan.find(params[:plan_id])
    end

    def charge_params
      params.permit(:name, :fee)
    end

    def validate_plan_inactiveness
      render json: {plan: ['缴费中']}, status: :unprocessable_entity if (@plan || @charge.plan).active?
    end
  end
end